package com.ruoyi.generator.util;/**
 * Created by NINGMEI on 2024/1/17.
 */

import com.ruoyi.generator.domain.GenSqlColumn;
import com.ruoyi.generator.domain.GenSqlTable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @Author NINGMEI
 * @Date 2024/1/17 17:39
 * @Description
 */
@Component
@Slf4j
public class GenSqlTableUtil {

    @Value("${spring.datasource.driverClassName}")
    private String driver;
    @Value("${spring.datasource.druid.master.url}")
    private String url;
    @Value("${spring.datasource.druid.master.username}")
    private String username;
    @Value("${spring.datasource.druid.master.password}")
    private String password;
    public void genSqlTable(GenSqlTable table){
        Connection conn = null;
        Statement st = null;
        /**
         * 根据自己的MySQL版本选择
         * JDBC连接Mysql5：com.mysql.jdbc.Driver
         * JDBC连接Mysql6：com.mysql.cj.jdbc.Driver
         */
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
            st = conn.createStatement();
            List<GenSqlColumn> tableColumn = table.getTableColumn();
            AtomicBoolean priamayKey = new AtomicBoolean(false);
            StringBuffer buffer = new StringBuffer();
            buffer.append("`id` bigint NOT NULL AUTO_INCREMENT COMMENT "+"'主键id',");
            priamayKey.set(true);
            tableColumn.stream().forEach(item -> {
                buffer.append("`");
                buffer.append(item.getColumnName())
                        .append("` ")
                        .append(item.getColumnType());
                if (item.getColumnLength()!=null&& !Objects.equals(item.getColumnType(), "decimal")){
                    buffer.append("(").append(item.getColumnLength()).append(")");
                }
                if (item.getColumnLength()!=null&& Objects.equals(item.getColumnType(), "decimal")){
                    buffer.append("(").append(item.getColumnLength()).append(",").append(item.getColumnPoint()).append(")");
                }
                buffer.append(" ");
                if (item.getColumnIsNull()){
                    buffer.append("NOT NULL").append(" ");
                }

                if (!item.getColumnComment().isEmpty()){
                    buffer.append("COMMENT '").append(item.getColumnComment()).append("' ,");
                }
            });
            buffer.append("`remark` varchar(255) COMMENT "+"'备注',");
            buffer.append("`create_by` varchar(255) NULL COMMENT '创建者',");
            buffer.append("`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',");
            buffer.append("`update_by` varchar(255) NULL COMMENT '更新者',");
            buffer.append("`update_time` datetime NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',");
            buffer.append("`is_delete` tinyint DEFAULT 0 COMMENT '逻辑删除(0表示未删除，1表示软删除)',");
            buffer.append("  PRIMARY KEY (`id`)");
            st.addBatch(getCreateTableSql(table.getTableName(), table.getTablePrefix(), priamayKey.get(), buffer.toString(),table.getTableComment()) );

            st.executeBatch();
        } catch (Exception e) {
            System.out.println("执行出现错误：conn - 》" + conn + "，st - 》" + st);
        } finally {
            try {
                if (st != null) st.close();
                if (conn != null) conn.close();
            } catch (Exception ex) {

            }
        }
    }
    /**
     * 拼接创建表格SQL
     * @param tableName 数据库表名
     * @param tableNamePrefix   表名前面动态拼接唯一标识（不用，可以删除）
     * @param primaryKey    主键字段
     * @return
     */
    private static String getCreateTableSql(String tableName, String tableNamePrefix, boolean primaryKey, String buffer, String tableComment) {
        StringBuffer sql = new StringBuffer();
        sql.append("CREATE TABLE IF NOT EXISTS ");
        if (tableNamePrefix != null) {
            sql.append(tableNamePrefix);
        }
        sql.append(tableName).append("(");
        sql.append(buffer);
        sql.append(")").append(" engine=innodb");
        if (primaryKey){
//             = " " + tableNamePrefix + tableName + "(%s, PRIMARY KEY (`"+primaryKey+"`))"
//             comment = '角色信息表'
            sql.append(" auto_increment=1 ");
        }
        if (tableComment!=null){
            sql.append("COMMENT '").append(tableComment).append("';");
        }
        log.info("sql为：{}",sql);
        return sql.toString();
    }

}
